from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
from jose import JWTError, jwt
from app.core.config import settings
from app.crud.user import get_user_by_username


async def jt_token_middleware(request: Request, call_next):
    # 白名单路由，不需要认证
    WHITELIST = [
        "/api/v1/auth/login",
        "/docs",
        "/openapi.json",
        "/favicon.ico"
    ]

    if request.url.path in WHITELIST:
        return await call_next(request)

    try:
        # 从JT-token头获取token
        jt_token = request.headers.get("JT-token")
        if not jt_token:
            return JSONResponse(
                status_code=1401,
                content={"msg": "未传token"}
            )

        # 解码并验证token
        payload = jwt.decode(jt_token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        username = payload.get("id")
        if not username:
            return JSONResponse(
                status_code=1401,
                content={"msg": "token 错误"}
            )

        # 获取用户并检查状态
        user = get_user_by_username(username)
        if not user or not user.is_active:
            return JSONResponse(
                status_code=1401,
                content={"msg": "认证失败或用户未激活"}
            )

        # 将用户信息存入request.state
        request.state.current_user = user

        # 继续处理请求
        response = await call_next(request)
        return response

    except JWTError as e:
        return JSONResponse(
            status_code=1401,
            content={"msg": f"token错误: {str(e)}"}
        )
    except Exception as e:
        return JSONResponse(
            status_code=1500,
            content={"msg": f"系统错误: {str(e)}"}
        )